package cn.hfuu;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author oldliu
 * @since 1.0
 */
public class NumMax {
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        if (args.length != 2) {
            System.out.println("using two arguments");
            return;
        }
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "numfind");
        job.setJarByClass(NumMax.class);
        job.setMapperClass(NumberMapper.class);
        job.setCombinerClass(NumberReducer.class);
        job.setReducerClass(NumberReducer.class);
        job.setOutputKeyClass(LongWritable.class);
        job.setOutputValueClass(NullWritable.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    static class NumberMapper extends Mapper<Object, Text, LongWritable, NullWritable> {
        private LongWritable max = new LongWritable(Long.MIN_VALUE);

        @Override
        protected void map(Object key, Text value, Mapper<Object, Text, LongWritable, NullWritable>.Context context) throws IOException, InterruptedException {
            long n = Long.parseLong(value.toString());
            if (max.get() < n) {
                max.set(n);
            }
        }

        @Override//所有的map任务执行结束时执行
        protected void cleanup(Mapper<Object, Text, LongWritable, NullWritable>.Context context) throws IOException,
                InterruptedException {
            context.write(max, NullWritable.get());
        }
    }

    static class NumberReducer extends Reducer<LongWritable, NullWritable, LongWritable, NullWritable> {
        private LongWritable max = new LongWritable(Long.MIN_VALUE);

        @Override
        protected void reduce(LongWritable key, Iterable<NullWritable> values, Reducer<LongWritable, NullWritable,
                LongWritable, NullWritable>.Context context) throws IOException, InterruptedException {
            if (max.get() < key.get()) {
                max.set(key.get());
            }
        }

        @Override
        protected void cleanup(Reducer<LongWritable, NullWritable, LongWritable, NullWritable>.Context context) throws IOException, InterruptedException {
            context.write(max, NullWritable.get());
        }
    }
}
